package com.example.armmvvm.ui.fallview

import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.lifecycle.DefaultLifecycleObserver
import androidx.lifecycle.Lifecycle
import androidx.lifecycle.LifecycleOwner
import kotlinx.coroutines.Job
import kotlinx.coroutines.MainScope
import kotlinx.coroutines.cancel
import kotlin.collections.set

/**
 *  author : yanghaozhang
 *  date : 2022/10/19 11:26
 *  description :
 */

const val SHOW_TIME_POST_DELAYED = 100L

const val DISMISS_TIME_POST_DELAYED = 156L

abstract class BaseFallViewController<T : IFallViewSetting>(
    protected val viewContainer: ViewGroup,
    protected val lifecycleOwner: LifecycleOwner
) :
    IFallViewController<T>, DefaultLifecycleObserver {

    protected var doingJob: Job? = null

    protected val coroutineScope = MainScope()

    protected val viewList: MutableMap<Int, View> = mutableMapOf()

    override fun attachView(layoutId: Int): View {
        return viewList[layoutId] ?: LayoutInflater.from(viewContainer.context).inflate(layoutId, viewContainer, false).also {
            viewList[layoutId] = it
        }
    }

    override fun onDestroy(owner: LifecycleOwner) {
        onDestroy()
    }

    override fun onDestroy() {
        lifecycleOwner.lifecycle.removeObserver(this)
        coroutineScope.cancel()
        viewList.clear()
    }

    protected fun isDestroy() = lifecycleOwner.lifecycle.currentState == Lifecycle.State.DESTROYED
}